package com.joplus.housekeeper.utils;

import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.ImageFormat;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;
import android.util.Base64;
import android.util.Log;
import android.widget.ImageView;

import com.joplus.housekeeper.R;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.display.SimpleBitmapDisplayer;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

/**
 * Created by tangdehao on 16/5/11.
 */
public class Imageutils {

    /**
     * 保存方法
     */
    public static File saveBitmap(Bitmap bitmap) {

        File skRoot = Environment.getExternalStorageDirectory();

        File f = new File(skRoot, "jo_user.png");

        if (f.exists()) {
            f.delete();
        }
        try {
            FileOutputStream out = new FileOutputStream(f);
            bitmap.compress(Bitmap.CompressFormat.PNG, 90, out);
            out.flush();
            out.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();

        } catch (IOException e) {
            e.printStackTrace();

        }
        return f;
    }

    public static File savePic(Bitmap btImage) {


        String s = System.currentTimeMillis() + ".jpg";
        File file = new File(Environment.getExternalStorageDirectory().getAbsoluteFile() + "/image/" + s);
        file.getParentFile().mkdirs();
        FileOutputStream out = null;
        try {
            out = new FileOutputStream(file);
            btImage.compress(Bitmap.CompressFormat.JPEG, 100, out);
            System.out.println("___________保存的__sd___下_______________________");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        try {
            out.flush();
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return file;
        //Toast.makeText(HahItemActivity.this,"保存已经至"+Environment.getExternalStorageDirectory()+"下", Toast.LENGTH_SHORT).show();
    }

    public static File savePic(Bitmap btImage, File file) {



        FileOutputStream out = null;
        try {
            out = new FileOutputStream(file);
            btImage.compress(Bitmap.CompressFormat.JPEG, 100, out);
            System.out.println("___________保存的__sd___下_______________________");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        try {
            out.flush();
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return file;
        //Toast.makeText(HahItemActivity.this,"保存已经至"+Environment.getExternalStorageDirectory()+"下", Toast.LENGTH_SHORT).show();
    }


    public static File saveBitmap(Bitmap bitmap, String name) {

        File skRoot = Environment.getExternalStorageDirectory();
        Log.e("saveBitmap", skRoot.getAbsolutePath());
        File f = new File(skRoot, "jo_user.png");
        if (f.exists()) {
            f.delete();
        }
        try {
            FileOutputStream out = new FileOutputStream(f);
            bitmap.compress(Bitmap.CompressFormat.PNG, 90, out);
            out.flush();
            out.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();

        } catch (IOException e) {
            e.printStackTrace();

        }
        return f;
    }

    public static File stringtoBitmap(String string) {
        //将字符串转换成Bitmap类型
        Bitmap bitmap = null;
        File file = null;
        try {
            byte[] bitmapArray;
            bitmapArray = Base64.decode(string, Base64.DEFAULT);
            bitmap = BitmapFactory.decodeByteArray(bitmapArray, 60, bitmapArray.length);
            file = saveBitmap(bitmap, "new.jpg");
        } catch (Exception e) {
            e.printStackTrace();
        }

        return file;
    }

    /**
     * 通过BASE64Decoder解码，并生成图片
     *
     * @param imgStr 解码后的string
     */
    public static File string2Image(String imgStr, File imgFilePath) {
        // 对字节数组字符串进行Base64解码并生成图片


        try {
            // Base64解码
            byte[] b = Base64.decode(imgStr.getBytes(), Base64.DEFAULT);
           /* for (int i = 0; i < b.length; ++i) {
                if (b[i] < 0) {
                    // 调整异常数据
                    b[i] += 256;
                }
            }*/
            // 生成Jpeg图片
            FileOutputStream out = new FileOutputStream(imgFilePath);
            out.write(b);
            out.flush();
            out.close();
            Log.e("path", "string2Image: " + imgFilePath.exists() + imgFilePath.length());
            return imgFilePath;
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 保存方法
     */
    public static File saveBitmap4advertisement(Bitmap bitmap) {

        File skRoot = Environment.getExternalStorageDirectory();
        File f = new File(skRoot, "advertisement.png");
        if (f.exists()) {
            f.delete();
        }
        try {
            FileOutputStream out = new FileOutputStream(f);
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
            out.flush();
            out.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();

        } catch (IOException e) {
            e.printStackTrace();

        }
        return f;
    }


    public static void loaderHeadPic(String headPic, ImageView imageView) {
        DisplayImageOptions options = new DisplayImageOptions.Builder()
                .showImageForEmptyUri(R.drawable.jo_defaule_user_icon) // 设置图片Uri为空或是错误的时候显示的图片
                .showImageOnFail(R.drawable.jo_defaule_user_icon) // 设置图片加载或解码过程中发生错误显示的图片
                .resetViewBeforeLoading(false)  // default 设置图片在加载前是否重置、复位
                .delayBeforeLoading(0)  // 下载前的延迟时间
                .cacheOnDisk(true) // default  设置下载的图片是否缓存在SD卡中
                .considerExifParams(false) // default
                .imageScaleType(ImageScaleType.EXACTLY) // default 设置图片以如何的编码方式显示
                .bitmapConfig(Bitmap.Config.ARGB_8888) // default 设置图片的解码类型
                .displayer(new SimpleBitmapDisplayer()) // default  还可以设置圆角图片new RoundedBitmapDisplayer(20)
                .handler(new Handler()) // default
                .build();
        ImageLoader.getInstance().displayImage(headPic, imageView, options);
    }

    public static void loaderHeadPicMenu(String headPic, ImageView imageView) {
        DisplayImageOptions options = new DisplayImageOptions.Builder()
                .showImageForEmptyUri(R.drawable.userhead) // 设置图片Uri为空或是错误的时候显示的图片
                .showImageOnFail(R.drawable.userhead) // 设置图片加载或解码过程中发生错误显示的图片
                .resetViewBeforeLoading(false)  // default 设置图片在加载前是否重置、复位
                .delayBeforeLoading(0)  // 下载前的延迟时间
                .cacheOnDisk(true) // default  设置下载的图片是否缓存在SD卡中
                .considerExifParams(false) // default
                .imageScaleType(ImageScaleType.EXACTLY) // default 设置图片以如何的编码方式显示
                .bitmapConfig(Bitmap.Config.ARGB_8888) // default 设置图片的解码类型
                .displayer(new SimpleBitmapDisplayer()) // default  还可以设置圆角图片new RoundedBitmapDisplayer(20)
                .handler(new Handler()) //     default
                .build();
        ImageLoader.getInstance().displayImage(headPic, imageView, options);
    }


    public static String getRealFilePath(final Context context, final Uri uri) {
        if (null == uri) return null;
        final String scheme = uri.getScheme();
        String data = null;
        if (scheme == null)
            data = uri.getPath();
        else if (ContentResolver.SCHEME_FILE.equals(scheme)) {
            data = uri.getPath();
        } else if (ContentResolver.SCHEME_CONTENT.equals(scheme)) {
            Cursor cursor = context.getContentResolver().query(uri, new String[]{MediaStore.Images.ImageColumns.DATA}, null, null, null);
            if (null != cursor) {
                if (cursor.moveToFirst()) {
                    int index = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
                    if (index > -1) {
                        data = cursor.getString(index);
                    }
                }
                cursor.close();
            }
        }
        return data;
    }

    public static Bitmap rotateBitmap(Bitmap paramBitmap, int paramInt) {
        if ((paramInt == 0) || (paramBitmap == null))
            return paramBitmap;
        Matrix localMatrix = new Matrix();
        localMatrix.setRotate(paramInt, paramBitmap.getWidth() / 2, paramBitmap.getHeight() / 2);
        Bitmap localBitmap = Bitmap.createBitmap(paramBitmap, 0, 0, paramBitmap.getWidth(), paramBitmap.getHeight(), localMatrix, true);
        if (paramBitmap != null)
            paramBitmap.recycle();
        return localBitmap;
    }

    public static int readPictureDegree(String paramString) {
        try {
            int i = new ExifInterface(paramString).getAttributeInt("Orientation", 1);
            switch (i) {
                case 4:
                case 5:
                case 7:
                default:
                    return 0;
                case 3:
                    return 180;
                case 6:
                    return 90;
                case 8:
            }
            return 270;
        } catch (IOException localIOException) {
            localIOException.printStackTrace();
        }
        return 0;
    }

    public static Bitmap decodeFile(String paramString) {
        try {
            File localFile = new File(paramString);
            System.out.println("图片压缩前: " + localFile.length() / 1024L);
            BitmapFactory.Options localOptions1 = new BitmapFactory.Options();
            localOptions1.inJustDecodeBounds = true;
            FileInputStream localFileInputStream1 = new FileInputStream(localFile);
            BitmapFactory.decodeStream(localFileInputStream1, null, localOptions1);
            localFileInputStream1.close();
            int i = 1;
            int j = localOptions1.outWidth;
            int k = localOptions1.outHeight;
            while (true) {
                if ((j / 2 < 100) || (k / 2 < 100)) {
                    BitmapFactory.Options localOptions2 = new BitmapFactory.Options();
                    localOptions2.inSampleSize = i;
                    FileInputStream localFileInputStream2 = new FileInputStream(localFile);
                    Bitmap localBitmap = BitmapFactory.decodeStream(localFileInputStream2, null, localOptions2);
                    localFileInputStream2.close();
                    return localBitmap;
                }
                j /= 2;
                k /= 2;
                i *= 2;
            }
        } catch (IOException localIOException) {
            localIOException.printStackTrace();
            return null;
        }
    }

    //计算图片的缩放值
    public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
        final int height = options.outHeight;
        final int width = options.outWidth;
        int inSampleSize = 1;

        if (height > reqHeight || width > reqWidth) {
            final int heightRatio = Math.round((float) height / (float) reqHeight);
            final int widthRatio = Math.round((float) width / (float) reqWidth);
            inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
        }
        return inSampleSize;
    }

    // 根据路径获得图片并压缩，返回bitmap用于显示
    public static Bitmap getSmallBitmap(String filePath) {
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(filePath, options);

        // Calculate inSampleSize
        options.inSampleSize = calculateInSampleSize(options, 480, 800);

        // Decode bitmap with inSampleSize set
        options.inJustDecodeBounds = false;

        return BitmapFactory.decodeFile(filePath, options);
    }

    //把bitmap转换成String
    public static String bitmapToString(String filePath) {

        Bitmap bm = getSmallBitmap(filePath);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bm.compress(Bitmap.CompressFormat.JPEG, 40, baos);
        byte[] b = baos.toByteArray();
        return Base64.encodeToString(b, Base64.DEFAULT);
    }
}
